#! /usr/bin/python

# bird.py

"""Upload the contents of a bird list in date order
to a database.  It is built around updating
a birder's lifelist.

You can run this module as a stand alone script:
Options:
  -h, --help              show this help
  -d ..., --database=...  specify a database (defaults to birdlist)
  -t ..., --table=...     specify a table within the database (defaults to lifeList)

Or you can run bird_up.py which provides a gui framework
to extend this module.  It provides a great deal of functionality
and could be easily configurable for other purposes.

This program comes with ABSOLUTELY NO WARRANTY.
    This is free software, and you are welcome to redistribute it
    under certain conditions.\n"""
# Imports
import sqlite3 as lite
import wx
import os
import sys
import getopt


class EachBird:
    def __init__(self, dbase='', table=''):
        # The birdlist_db.txt file is just a holder for the datase
        # and table normally used by the user.
        thisPath = sys.path[0]
        self.DBandTableVals = os.path.join(thisPath, 'birdlist_db.txt')
        try:
            if dbase == '' or table == '':
                dbase = dbase or open(self.DBandTableVals, 'r').readlines()[0].strip()
                table = table or open(self.DBandTableVals, 'r').readlines()[1].strip()
        except:
            # if the user sets not tables and the file isn't created yet, it just makes some up.
            # in the gui we could later prompt users for a value for each.
            dbase = 'birdlist'
            table = 'BirdListTable'
        self.writeDatabase = open(self.DBandTableVals, 'w')
        # Regarless if they are changed or not, I write to the file
        self.writeDatabase.write(dbase + "\n" + table)
        self.writeDatabase.close()
        
        self.dbase = dbase
        self.table = table
        self.makeNewDatabase()
        self.bird_name = ""
        self.scientific_name = ""
        self.date_observed = []
        self.PlaceTownCountry = []
        self.notes = ""
        
    def makeNewDatabase(self):
        """Opens the database, creating it if it doesn't exist
        then checking to see if the table exists, creating it if it doesn't"""
        con = lite.connect("%s" % self.dbase)
        cur = con.cursor()
        # check if the talble exists with the if not exits in the query.
        mtquery = "create table if not exists %s(key INTEGER PRIMARY KEY, cn text, sn text, day text, month text, year text, place text, town text, country text, notes text)" % self.table
        cur.execute(mtquery)
        con.commit()
        cur.close()
        con.close()
        
    def getMostRecent(self):
        """Get the most recent entry"""
        con = lite.connect(self.dbase)
        cur = con.cursor()
        cur.execute('select cn from %s order by key desc;' % self.table)
        latest_bird = cur.fetchone()
        cur.close()
        con.close()
        return latest_bird[0]
        
    def getData(self):
        """Each bird on my life list will be represented as an instance of the class
        In this method we aquire the values for each attribute of the class
        This includes:
            Common Name
            Scientific Name
            date observed [as day, month, year] list
            Place observed [as place, town, country], where town is optional
            My notes on the sighting
        It is mainly about being able to record something special and share it,
        but it can be built on for others to uses.
        
        """
        self.bird_name = raw_input("Common Name ->  ")
        self.bird_name = " ".join([nms.capitalize() for nms in self.bird_name.split()])
        self.scientific_name = raw_input("Scientific Name ->  ")
        self.scientific_name = self.scientific_name.capitalize()
        self.date_observed = [raw_input("Day ->  "), raw_input("Month -> "), raw_input("Year -> ")]
        self.date_observed[1] = self.monthChecker(self.date_observed[1])
        self.PlaceTownCountry = [raw_input("What Place ->  "),  
                                 raw_input("What town - leave blank if none ->  "), 
                                 raw_input("What country ->  ")]
        
        self.notes = raw_input("Notes ->  ")
    def storeData(self):
        """Take the data and put it up to a database"""
        # database: birdlist, table lifeList(key INTEGER PRIMARY KEY, cn text, sn text, day text, month text, year text, place text, town text, country, notes text);
        con = lite.connect(self.dbase)
        cur = con.cursor()        
        query = """INSERT INTO %s (key, cn, sn, day, month, year, place, town, country, notes) Values (NULL,"%s","%s","%s","%s","%s","%s","%s","%s","%s")""" %\
        (self.table,\
         self.bird_name,\
         self.scientific_name,\
         self.date_observed[0],\
         self.date_observed[1],\
         self.date_observed[2],\
         self.PlaceTownCountry[0],\
         self.PlaceTownCountry[1],\
         self.PlaceTownCountry[2],\
         self.notes)
        cur.execute(query)
        con.commit()
        cur.close()
        con.close()
        
    def monthChecker(self, month):
        """This just allows different month formats to be entered and give the same result"""
        months = {'January':['january', 'jan', '1'],\
                  'February':['february', 'feb', '2'],\
                  'March':['march', 'mar', '3'],\
                  'April':['april', 'apr', '4'],\
                  'May':['may', '5'],\
                  'June':['june', 'jun', '6'],\
                  'July':['july', 'jul', '7'],\
                  'August':['august', 'aug', '8'],\
                  'September':['september', 'sep', '9'],\
                  'October':['october', 'oct', '10'],\
                  'November':['november', 'nov', '11'],\
                  'December':['december', 'dec', '12']}
        for k, v in months.items():
            if month.lower() in v:
                month = k
        return month
                


if __name__ == "__main__":
    tb, db = "", ""
    argv = sys.argv[1:]
    try:
        opts, args = getopt.getopt(argv, 'hd:t:', ['help', 'database=', 'table='])
    except getopt.GetoptError:
        print __doc__
        sys.exit()
    
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print __doc__
            sys.exit()
        elif opt in ('-d', '-database'):
            db = arg
        elif opt in ('-t', '-table'):
            tb = arg
    while True:
        bird = EachBird(dbase=db, table=tb)
        bird.getData()
        ready = raw_input("Are you sure you want to add this data to the database (y/n) ")
        if ready[0].lower() == "y":
            bird.storeData()
            go_on = raw_input("Would you like to add another bird (y/n) ")
            if go_on[0].lower() == "y":
                print "On to the next bird"
            else:
                print "\n\nOkay, Goodbye\n\n"
                break
        else:
            print "Enter the data again"